package cn.dankal.flyaudio.friend;

import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.StringUtils;
import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.v2.SelectDialog;

import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.MyCardServiceFactory;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ContractPersonAdapter;
import cn.dankal.flyaudio.adapter.ItemPickContractImgAdapter;
import cn.dankal.flyaudio.entity.GroupEntity;
import cn.dankal.flyaudio.friend.utils.HandleResponseCode;
import cn.dankal.flyaudio.friend.utils.ShareUtils;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.dankal.flyaudio.pop.FriendSharePop;
import cn.dankal.flyaudio.view.LetterNavView;
import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;

public class CreateNewConvActivity extends BaseActivity {

    private RecyclerView friendView, mRvUser;
    private LetterNavView navView;
    private ImageView rightIcon;
    private TextView rightText;
    private TextView titleView;

    private TextView searchTextView;

    private ClearEditText searchEditText;

    private MultipleStatusView statusView;

    private ContractPersonAdapter adapter;

    private ItemPickContractImgAdapter itemPickContractImgAdapter;

    private List<GroupEntity> personEntities = new ArrayList<>();

    List<GroupEntity> groupEntities = new ArrayList<>();

    private String couponId = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_create_new_conv;
    }

    @Override
    protected void initComponents() {
        couponId = getIntent().getStringExtra("couponId");
        friendView = findViewById(R.id.rv_friend);
        navView = findViewById(R.id.letter_container);
        mRvUser = findViewById(R.id.mRv_user);
        initSearch();
        rightText = findViewById(R.id.tv_confirm);
        mRvUser = findViewById(R.id.mRv_user);
        itemPickContractImgAdapter = new ItemPickContractImgAdapter();
        titleView = findViewById(R.id.tv_title);
        rightText.setVisibility(View.VISIBLE);
        rightText.setEnabled(false);
        titleView.setText("选择联系人");
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LiveEventBus.get("share", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                finishActivity();
            }
        });

        findViewById(R.id.rl_to_group).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startActivity(ShareGroupActivity.class);
            }
        });
        friendView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContractPersonAdapter(this, personEntities);
        if (!StringUtils.isEmpty(couponId)) {
            adapter.setPickModel(ContractPersonAdapter.MODEL_PICK);
            adapter.setSinglePick(true);
        } else {
            adapter.setPickModel(ContractPersonAdapter.MODEL_PICK);
        }

        friendView.setAdapter(adapter);
        mRvUser.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,
                false));
        mRvUser.setAdapter(itemPickContractImgAdapter);
        navView.setLetterChangeListener(new LetterNavView.LetterChangeListener() {
            @Override
            public void onTouchingLetterChanged(int index, String text) {
                int count = 0;
                for (int i = 0; i < index; i++) {
                    count++;
                    if (personEntities.isEmpty()) {
                        return;
                    }
                    count += personEntities.get(i).getChildren().size();
                }
                if (count != -1) {
                    friendView.scrollToPosition(count);
                    LinearLayoutManager mLayoutManager =
                            (LinearLayoutManager) friendView.getLayoutManager();
                    mLayoutManager.scrollToPositionWithOffset(count, 0);
                }
            }
        });
        adapter.setOnItemSelectListener(new ContractPersonAdapter.OnItemSelectListener() {
            @Override
            public void onSelect(List<UserInfo> userInfos) {
                itemPickContractImgAdapter.updateData(userInfos);
                if (userInfos.isEmpty()) {
                    rightText.setEnabled(false);
                    rightText.setClickable(false);
                } else {
                    rightText.setEnabled(true);
                    rightText.setClickable(true);
                }
            }
        });

        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isEmpty(couponId)) {
                    List<UserInfo> userInfos = adapter.getPickMember();
                    if (userInfos.isEmpty()) {
                        ToastUtils.showShort("请选择");
                        return;
                    }
                    sendCoupon(adapter.getPickMember().get(0));
                } else {
                    List<Conversation> conversations = new ArrayList<>();
                    for (UserInfo userInfo : adapter.getPickMember()) {
                        if (JMessageClient.getSingleConversation(userInfo.getUserName()) == null) {
                            conversations.add(Conversation.createSingleConversation(userInfo.getUserName()));
                        } else {
                            conversations.add(JMessageClient.getSingleConversation(userInfo.getUserName()));
                        }
                    }
                    //发送
                    new FriendSharePop(CreateNewConvActivity.this)
                            .setConversation(conversations)
                            .setShareFile(ShareUtils.getInstance().getFile())
                            .setDoSendListener(new FriendSharePop.DoSendListener() {
                                @Override
                                public void doSend(String content) {
                                    ImageContent.createImageContentAsync(ShareUtils.getInstance().getFile(), new ImageContent.CreateImageContentCallback() {
                                        @Override
                                        public void gotResult(int responseCode, String responseMessage, ImageContent imageContent) {
                                            if (responseCode == 0) {
                                                ToastUtils.showShort("发送成功");
                                                for (Conversation conversation : conversations) {
//                                                    imageContent.setStringExtra("jiguang", "xiong");
                                                    Message msg = conversation.createSendMessage(imageContent);
                                                    JMessageClient.sendMessage(msg);
                                                    if (!StringUtils.isEmpty(content)) {
                                                        conversation.createSendTextMessage(content);
                                                    }
                                                }
                                                LiveEventBus.get("share", String.class).post("");
                                                finishActivity();
                                            } else {
                                                ToastUtils.showShort(responseMessage);
                                            }
                                        }
                                    });
                                }
                            })
                            .setPopupGravity(Gravity.CENTER)
                            .showPopupWindow(findViewById(android.R.id.content));
                }
            }
        });
        ContactManager.getFriendList(new GetUserInfoListCallback() {
            @Override
            public void gotResult(int i, String s, List<UserInfo> list) {
                handleFriend(list);
            }
        });
    }

    private List<UserInfo> friendList = new ArrayList<>();

    private void sendCoupon(UserInfo userInfo) {
        SelectDialog.show(CreateNewConvActivity.this, "提示", "是否赠送此优惠券!", "确定", (dialog, which) -> {
            doSendReq(couponId, userInfo.getUserName(), userInfo.getNickname());
        }, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
    }

    private void toChatBySingle(String title, String username) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(FlyApplication.CONV_TITLE, "");
        intent.putExtra(FlyApplication.TARGET_ID, username);
        startActivity(intent);
    }

    private void toChatByGroup(String title, long groupId) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(FlyApplication.CONV_TITLE, title);
        intent.putExtra(FlyApplication.GROUP_ID, groupId);
        startActivity(intent);
    }

    private void send(String transferOrderUuid, String username, String nickName) {
        CustomContent customContent = new CustomContent();
        customContent.setStringExtra("coupon_id", transferOrderUuid);
        customContent.setStringExtra("sendCoupon", "sendCoupon");
        Conversation conversation = JMessageClient.getSingleConversation(username);
        Message textMessage = conversation.createSendMessage(customContent);
        MessageSendingOptions options = new MessageSendingOptions();
        options.setNeedReadReceipt(true);
        JMessageClient.sendMessage(textMessage, options);
        textMessage.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    SharePreferenceManager.setIsOpen(true);
                    LiveEventBus.get("share", String.class).post("");
                    Toast.makeText(CreateNewConvActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    toChatBySingle(nickName, username);
                    finish();
                } else {
                    HandleResponseCode.onHandle(CreateNewConvActivity.this, i, false);
                }
            }
        });
    }

    private void doSendReqByGroup(String couponId, String groupId) {
        showLoadingDialog();
//        MyCardServiceFactory.couponsExchangeByGroup(couponId, groupId)
//                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
//                    @Override
//                    public void onNext(BaseResponse<String> objectBaseResponse) {
//                        dismissLoadingDialog();
//                        ToastUtils.showShort("发送成功");
//                        send(objectBaseResponse.getData());
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        dismissLoadingDialog();
//                        super.onError(e);
//                    }
//                });
    }

    private void doSendReq(String couponId, String userId, String nickName) {
        showLoadingDialog();
        MyCardServiceFactory.couponsExchange(couponId, userId)
                .subscribe(new AbstractSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void onNext(BaseResponse<String> objectBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("发送成功");
                        send(objectBaseResponse.getData(), userId, nickName);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        super.onError(e);
                    }
                });
    }

    private void initSearch() {
        statusView = findViewById(R.id.multiple_status_view);
        searchTextView = findViewById(R.id.tv_search);
        searchEditText = findViewById(R.id.et_search);
        searchEditText.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (TextUtils.isEmpty(keyword)) return;
                mDoSearch(keyword);
            }
        });
        searchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = searchEditText.getText().toString();
                if (TextUtils.isEmpty(key)) return;
                mDoSearch(key);
            }
        });
        searchEditText.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (TextUtils.isEmpty(s)) {
                    friendView.setAdapter(adapter);
                    statusView.showContent();
                }
            }
        });
        statusView.showContent();
    }

    private void mDoSearch(String key) {
        List<UserInfo> searResult = new ArrayList<>();
        for (UserInfo userInfo : friendList) {
            ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                    .get(userInfo.getNickname());
            StringBuilder sb = new StringBuilder();
            if (tokens != null && tokens.size() > 0) {
                for (HanziToPinyin.Token token : tokens) {
                    if (token.type == HanziToPinyin.Token.PINYIN) {
                        sb.append(token.target);
                    } else {
                        sb.append(token.source);
                    }
                }
            }
            if (sb.toString().contains(key) || userInfo.getNickname().contains(key)) {
                searResult.add(userInfo);
            }
        }
        if (searResult.isEmpty()) {
            statusView.showEmpty();
        }
    }


    private void handleFriend(List<UserInfo> list) {
        friendList.clear();
        friendList.addAll(list);
        groupEntities.clear();
        for (UserInfo userInfo : list) {
            String letter = getLetter(userInfo.getNickname());
            if (!checkGroupSave(letter)) {
                GroupEntity groupEntity = new GroupEntity();
                groupEntity.setHeader(letter);
                groupEntities.add(groupEntity);
            }
            GroupEntity groupEntity = getGroupByLetter(letter);
            if (groupEntity != null) {
                List<UserInfo> userInfos = groupEntity.getChildren();
                userInfos.add(userInfo);
                groupEntity.setChildren(userInfos);
            }
        }
        adapter.setNewData(groupEntities);
    }

    private boolean checkGroupSave(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return true;
            }
        }
        return false;
    }

    private GroupEntity getGroupByLetter(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return entity;
            }
        }
        return null;
    }

    private String getLetter(String name) {
        String letter;
        ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                .get(name);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanziToPinyin.Token token : tokens) {
                if (token.type == HanziToPinyin.Token.PINYIN) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        String sortString = sb.toString().substring(0, 1).toUpperCase();
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase();
        } else {
            letter = "#";
        }
        return letter;
    }
}
